package tt.dz.biz.service.rpc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;

import java.util.Date;
import java.util.List;
import javax.annotation.Resource;
import org.apache.avro.Protocol;
import org.apache.avro.Protocol.Message;
import org.apache.avro.generic.GenericRecord;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import tt.dz.biz.dao.financial.MerchantDAO;
import tt.dz.biz.dao.verifycode.MsVerifyCodeDAOImp;
import tt.dz.biz.service.common.CommonService;
import tt.dz.biz.service.smsConfigure.SmsConfigureService;
import tt.dz.biz.service.smssend.SendMessageI;
import tt.dz.biz.service.smssend.SendSMSMessageFactory;
import tt.dz.common.DZStringUtil;
import tt.dz.common.DzErrorCode;
import tt.dz.common.DzErrorCode.CommonErrorCode;
import tt.dz.common.DzErrorCode.UserErrorCode;
import tt.dz.common.LogUtil;
import tt.dz.vo.MerchantVO;
import tt.dz.vo.SmsConfigureVO;
import tt.dz.vo.SmsSendRecord;
import tt.dz.vo.VerifyCodeVO;

@Service("rpcMsVerifyCodeService")
public class RPCMsVerifyCodeService
  implements RPCBaseService
{
  @Resource(name="msVerifyCodeDAO")
  private MsVerifyCodeDAOImp msVerifyCodeDAO;
  @Resource(name="sendSMSMessageFactory")
  private SendSMSMessageFactory sendSMSMessageFactory;
  @Resource(name="commonService")
  private CommonService commonService;
  @Resource(name="smsConfigureService")
  public SmsConfigureService smsConfigureService;
  @Value("${ms.sms.register}")
  private String MESSAGE_TEMPLATE;
  private static final String DEFAULT_OPERATION = "验证码";
  private static final String DEFAULT_MESSAGE_TEMPLATE = "【%s】%s:%s,验证码有效期为5分钟";
  @Autowired
  @Qualifier("merchantDAO")
  private MerchantDAO merchantDAO;
  
  public Object execute(Protocol.Message message, Object request, Protocol protocol)
  {
    String name = message.getName();
    Object reqJson = ((GenericRecord)request).get("req");
    String resJson = "";
    if ("getCheckCode".equals(name))
    {
      JSONObject reqObj = JSON.parseObject(reqJson.toString());
      if (!reqObj.containsKey("operation")) {
        reqObj.put("operation", "验证码");
      }
      resJson = JSON.toJSONString(getCheckCode(reqObj));
    }
    if ("verifyCheckCode".equals(name))
    {
      JSONObject reqObj = JSON.parseObject(reqJson.toString());
      resJson = JSON.toJSONString(verifyCheckCode(reqObj));
    }
    return resJson;
  }
  
  public JSONObject getCheckCode(JSONObject reqObj)
  {
    JSONObject resObj = new JSONObject();
    
    this.MESSAGE_TEMPLATE = (this.MESSAGE_TEMPLATE != null ? this.MESSAGE_TEMPLATE : "【%s】%s:%s,验证码有效期为5分钟");
    String mobileNo = reqObj.getString("mobileNo");
    String operation = reqObj.getString("operation");
//    String merchantCode = "120161012";
    String merchantCode = reqObj.getString("merchantCode");
    MerchantVO merchantVO = this.merchantDAO.queryMerchantByCode(merchantCode);
    if (null == merchantVO)
    {
      resObj.put("isSuccess", Integer.valueOf(0));
      resObj.put("errorMsg", DzErrorCode.CommonErrorCode.MISS_MERCHANT_ERROR.getDesc());
      resObj.put("errorCode", DzErrorCode.CommonErrorCode.MISS_MERCHANT_ERROR.value());
      return resObj;
    }
    String merchantName = "交投";
//    String merchantName = merchantVO.getShortName();
    merchantName = StringUtils.isEmpty(merchantName) ? "豪特" : merchantName;
    Date sendTime = this.commonService.getDBCurrentTime();
    Date overTime = new Date(sendTime.getTime() + 300000L);
    String checkCode = DZStringUtil.getRandomCode();
    String content = String.format(this.MESSAGE_TEMPLATE, new Object[] { merchantName, operation, checkCode });
    Integer isSuccess = Integer.valueOf(1);
    boolean issendOk = false;
    if (!DZStringUtil.verifyMobileNo(mobileNo))
    {
      resObj.put("isSuccess", Integer.valueOf(0));
      resObj.put("errorMsg", DzErrorCode.CommonErrorCode.MOBILE_NO_FORMAT_ERROR.getDesc());
      resObj.put("errorCode", DzErrorCode.CommonErrorCode.MOBILE_NO_FORMAT_ERROR.value());
      return resObj;
    }
    boolean isSendByOneMin = this.msVerifyCodeDAO.isSendByPhone(mobileNo);
    if (isSendByOneMin)
    {
      resObj.put("isSuccess", Integer.valueOf(0));
      resObj.put("errorMsg", "此手机号码在1分钟之内发送过短信请核实。");
      resObj.put("errorCode", DzErrorCode.CommonErrorCode.REPEAT_SEND_ERROR.value());
      return resObj;
    }
    try
    {
//      this.sendSMSMessageFactory.instance(merchantCode).sendMessage(mobileNo, content);
    	 DefaultProfile profile = DefaultProfile.getProfile("default", "LTAIE782weoj4u47", "CjTW3W3a7orAD7hFlGtcKs9KnXArq0");
         IAcsClient client = new DefaultAcsClient(profile);

         CommonRequest request = new CommonRequest();
         request.setMethod(MethodType.POST);
         request.setDomain("dysmsapi.aliyuncs.com");
         request.setVersion("2017-05-25");
         request.setAction("SendSms");
         request.putQueryParameter("PhoneNumbers", mobileNo);
         request.putQueryParameter("SignName", "充电APP");
//         request.putQueryParameter("SmsUpExtendCode", checkCode);
         request.putQueryParameter("TemplateParam", "{code:"+checkCode+"}");
         request.putQueryParameter("TemplateCode", "SMS_169405263");

         try {
             CommonResponse response = client.getCommonResponse(request);
             System.out.println(response.getData());
         } catch (ServerException e) {
             e.printStackTrace();
         } catch (ClientException e) {
             e.printStackTrace();
         }
      issendOk = true;
    }
    catch (Exception e)
    {
      isSuccess = Integer.valueOf(0);
      resObj.put("errorCode", DzErrorCode.CommonErrorCode.MESSAGE_SEND_ERROR.value());
      resObj.put("errorMsg", "发送短信发生异常,请稍后重试。");
      LogUtil.error("验证码发送异常，手机号码为：mobileNo=" + mobileNo, e);
    }
    if (issendOk)
    {
      saveSmsSendRecord(merchantCode, content, mobileNo);
      
      VerifyCodeVO verifyCodeVO = new VerifyCodeVO();
      verifyCodeVO.setMobileNo(mobileNo);
      verifyCodeVO.setSmsType(Integer.valueOf(1));
      
      verifyCodeVO.setContent(checkCode);
      verifyCodeVO.setSendTime(sendTime);
      verifyCodeVO.setOverTime(overTime);
      verifyCodeVO.setIsSuccess(isSuccess);
      verifyCodeVO.setSendTimes(Integer.valueOf(1));
      verifyCodeVO.setIsValid(Integer.valueOf(1));
      this.msVerifyCodeDAO.insertVerifyCode(verifyCodeVO);
      resObj.put("checkCode", checkCode);
    }
    resObj.put("mobileNo", mobileNo);
    resObj.put("isSuccess", isSuccess);
    return resObj;
  }
  
  private void saveSmsSendRecord(String merchantCode, String content, String mobileNo)
  {
    SmsSendRecord smsSendRecord = new SmsSendRecord();
    
    smsSendRecord.setMerchantCode(merchantCode);
    
    smsSendRecord.setMobileNo(mobileNo);
    
    SmsConfigureVO vo = getMerchantSmsConfig(merchantCode);
    if (null != vo) {
      smsSendRecord.setSmsChannel(vo.getSmsChannel());
    } else {
      smsSendRecord.setSmsChannel("YI_MEI");
    }
    smsSendRecord.setBusinessType("0");
    
    smsSendRecord.setMessageContent(content);
    
    smsSendRecord.setContentLength(content.length());
    
    smsSendRecord.setSendMessageTime(new Date());
    try
    {
      this.smsConfigureService.saveSmsSendRecord(smsSendRecord);
    }
    catch (Exception e)
    {
      LogUtil.error("保存短信发送记录发生异常", e);
    }
  }
  
  public JSONObject verifyCheckCode(JSONObject reqObj)
  {
    JSONObject resObj = new JSONObject();
    String mobileNo = reqObj.getString("mobileNo");
    String checkCode = reqObj.getString("checkCode");
    Integer isSuccess = Integer.valueOf(0);
    if (!DZStringUtil.verifyMobileNo(mobileNo))
    {
      resObj.put("isSuccess", isSuccess);
      resObj.put("errorCode", DzErrorCode.CommonErrorCode.MOBILE_NO_FORMAT_ERROR.value());
      resObj.put("errorMsg", "手机号码不合法。");
      return resObj;
    }
    VerifyCodeVO verifyCodeVO = this.msVerifyCodeDAO.getVerifyCodeByPhone(mobileNo);
    if (verifyCodeVO != null)
    {
      String content = verifyCodeVO.getContent();
      if ((content != null) && (!"".equals(content)) && 
        (checkCode.equals(content)))
      {
        isSuccess = Integer.valueOf(1);
      }
      else
      {
        resObj.put("errorCode", DzErrorCode.UserErrorCode.BAD_SMS_CODE.value());
        resObj.put("errorMsg", DzErrorCode.UserErrorCode.BAD_SMS_CODE.getDesc());
      }
    }
    else
    {
      resObj.put("errorCode", DzErrorCode.UserErrorCode.NOT_SEND_SMS_CODE.value());
      resObj.put("errorMsg", DzErrorCode.UserErrorCode.NOT_SEND_SMS_CODE.getDesc());
    }
    resObj.put("isSuccess", isSuccess);
    return resObj;
  }
  
  private SmsConfigureVO getMerchantSmsConfig(String merchantCode)
  {
    SmsConfigureVO vo = null;
    List<SmsConfigureVO> smsConfigVos = this.smsConfigureService.getConfigsByMerchantCode(merchantCode);
    if ((smsConfigVos != null) && (!smsConfigVos.isEmpty())) {
      vo = (SmsConfigureVO)smsConfigVos.get(0);
    }
    return vo;
  }
}
